import cv2
import numpy as np

BLACK_THRESHOLD = 135
WHITE_THRESHOLD = 150

RA = (0, 0)
RB = (0, 0)
RC = (0, 0)
RD = (0, 0)
E = (0, 0)
A = (0, 0)
C = (0, 0)
G = (0, 0)
I = (0, 0)
B = (0, 0)
F = (0, 0)
D = (0, 0)
H = (0, 0)

def preProcessing(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 1)
    _, threshold = cv2.threshold(blurred, 120, 255, cv2.THRESH_BINARY)
    return threshold

def getContours(img):
    global RA, RB, RC, RD, E, A, C, G, I, B, F, D, H
    biggest = np.array([])
    maxArea = 0
    contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area > 5000:
            perimeter = cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, 0.02 * perimeter, True)
            if len(approx) == 4 and area > maxArea:
                biggest = approx
                maxArea = area

    if biggest.size != 0:
        points = [tuple(point[0]) for point in biggest]
        RA, RB, RC, RD = points[0], points[1], points[2], points[3]

        E = (
            (RA[0] + RB[0] + RC[0] + RD[0]) / 4,
            (RA[1] + RB[1] + RC[1] + RD[1]) / 4
        )

        A = ((RA[0] + (E[0] - RA[0]) / 3), (RA[1] + (E[1] - RA[1]) / 3))
        C = ((RB[0] + (E[0] - RB[0]) / 3), (RB[1] + (E[1] - RB[1]) / 3))
        G = ((RC[0] + (E[0] - RC[0]) / 3), (RC[1] + (E[1] - RC[1]) / 3))
        I = ((RD[0] + (E[0] - RD[0]) / 3), (RD[1] + (E[1] - RD[1]) / 3))

        B = ((A[0] + C[0]) / 2, (A[1] + C[1]) / 2)
        F = ((C[0] + I[0]) / 2, (C[1] + I[1]) / 2)
        D = ((A[0] + G[0]) / 2, (A[1] + G[1]) / 2)
        H = ((G[0] + I[0]) / 2, (G[1] + I[1]) / 2)

        cv2.circle(img, (int(E[0]), int(E[1])), 5, (0, 255, 0), cv2.FILLED)

    return biggest

def getColor(img, point):
    window_size = 3
    half_window = window_size // 2
    black_count = 0
    white_count = 0
    px, py = int(point[0]), int(point[1])

    for i in range(-half_window, half_window + 1):
        for j in range(-half_window, half_window + 1):
            x = px + i
            y = py + j
            if 0 <= x < img.shape[1] and 0 <= y < img.shape[0]:
                b, g, r = img[y, x]
                if r < BLACK_THRESHOLD and g < BLACK_THRESHOLD and b < BLACK_THRESHOLD:
                    black_count += 1
                elif r > WHITE_THRESHOLD and g > WHITE_THRESHOLD and b > WHITE_THRESHOLD:
                    white_count += 1

    if black_count > white_count:
        return 1
    elif white_count > black_count:
        return 2
    else:
        return 0